import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/match/list/match_page_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';

import '../../widgets/base/qkd_text.dart';

class MatchFilterFloatWidget extends StatefulWidget {
  // ScrollController? scrollC;
  // MatchListProvider controller;
  //0 足球 1篮球
  final int type;
  final bool firstLoad;
  final QuickFilter matchType;
  final Function(QuickFilter index)? onTap;
  const MatchFilterFloatWidget(this.type, this.firstLoad, this.matchType,
      {super.key, this.onTap});

  @override
  State<MatchFilterFloatWidget> createState() => _MatchTypeWidgetState();
}

class _MatchTypeWidgetState extends State<MatchFilterFloatWidget> {
  //底部选择是否展开
  bool expandSelect = false;
  Timer? timer;
  bool hideSegment = true;

  // MatchListProvider controller = Get.find<MatchAllController>();

  @override
  void initState() {
    super.initState();
    // WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
    //   PrimaryScrollController.of(context).addListener(() {
    //     if (expandSelect) {
    //       setState(() {
    //         hideSegment = true;
    //         expandSelect = false;
    //         timer?.cancel();
    //       });
    //     }
    //   });
    // });
  }

  @override
  void dispose() {
    // widget.scrollC.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        SizedBox(
          width: Get.width,
          height: 36,
        ),
        segment(),
        if (!widget.firstLoad)
          Positioned(
            child: AnimatedOpacity(
              opacity: expandSelect ? 1 : 0,
              duration: const Duration(milliseconds: 300),
              child: Visibility(
                visible: !hideSegment,
                child: FloatExpandedWidget(
                  (index) {
                    timer?.cancel();
                    Future.delayed(const Duration(milliseconds: 500))
                        .then((value) => onExpand());
                    if (widget.onTap != null) {
                      widget.onTap!(QuickFilter.values[index]);
                    }
                  },
                  QuickFilter.values.indexOf(widget.matchType),
                  widget.type,
                  key: Key(widget.matchType.toString()),
                ),
              ),
            ),
          ),
      ],
    );
  }

  segment() {
    return AnimatedPositioned(
        // right: 8,
        right: expandSelect ? 100 : 8,
        duration: const Duration(milliseconds: 300),
        child: AnimatedOpacity(
          opacity: expandSelect ? 0 : 1,
          onEnd: () {
            if (!expandSelect) {
              hideSegment = true;
            }
          },
          duration: const Duration(milliseconds: 300),
          child: GestureDetector(
            onTap: () => onExpand(),
            child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(18),
                  gradient: const LinearGradient(
                      colors: [Color(0xFFF54D4F), Color(0xFFF53C6A)],
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter),
                ),
                alignment: Alignment.center,
                width: 68,
                height: 36,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset(
                      Utils.getImgPath(getMatchTypeImage(widget.matchType)),
                      width: 16,
                    ),
                    const SizedBox(width: 2),
                    QkdText(
                      widget.matchType.convertString(widget.type),
                      color: Colours.white, fontSize: 12,
                    )
                  ],
                )),
          ),
        ));
  }

  onExpand() {
    Utils.onEvent('bspd${widget.type == 0?'zq':'lq'}',params: {'bspd${widget.type == 0?'zq':'lq'}':8});
    hideSegment = !hideSegment;
    expandSelect = !expandSelect;
    if (expandSelect) {
      startTimer();
    }
    update();
  }

  startTimer() {
    if (timer != null) {
      timer?.cancel();
    }
    timer = Timer.periodic(const Duration(seconds: 4), (timer) {
      timer.cancel();
      onExpand();
    });
  }

  String getMatchTypeImage(QuickFilter type) {
    String matchTypeImage = 'match_select_quanbu.png';
    if (type == QuickFilter.yiji) {
      matchTypeImage = 'match_select_yiji.png';
    } else if (type == QuickFilter.jingcai) {
      matchTypeImage = 'match_select_jingzu.png';
    } else if (type == QuickFilter.qingbao){
      matchTypeImage = 'match_select_qingbao.png';
    } else if(type == QuickFilter.guandian){
      matchTypeImage = 'match_select_guandian.png';
    }
    return matchTypeImage;
  }
}

class FloatExpandedWidget extends StatefulWidget {
  final int initialIndex;
  final Function(int) onSelectIndex;
  final int type;
  const FloatExpandedWidget(this.onSelectIndex, this.initialIndex, this.type,
      {super.key});

  @override
  State<FloatExpandedWidget> createState() => _FloatExpandedWidgetState();
}

class _FloatExpandedWidgetState extends State<FloatExpandedWidget> {
  late int selectIndex;
  @override
  void initState() {
    super.initState();
    selectIndex = widget.initialIndex;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration:
          BoxDecoration(borderRadius: BorderRadius.circular(17), boxShadow: [
        BoxShadow(
            offset: const Offset(0, 4),
            color: Colours.main.withOpacity(0.1),
            blurRadius: 4)
      ]),
      height: 34,
      child: Stack(
        children: [
          Positioned(
            left: 2,
            right: 2,
            top: 1,
            bottom: 1,
            child: Container(
              height: 34,
              decoration: BoxDecoration(
                  border: Border.all(
                      color: Colours.main.withOpacity(0.4), width: 0.5),
                  borderRadius: BorderRadius.circular(17),
                  color: Colours.white),
            ),
          ),
          Row(children: [
            item('全部', 'match_select_quanbu.png', 0),
            item('一级', 'match_select_yiji.png', 1),
            item(widget.type == 0 ? '竞足' : '竞篮', 'match_select_jingzu.png', 2),
            item('爆料', 'match_select_qingbao.png', 3),
            item('方案', 'match_select_guandian.png', 4)
          ]),
        ],
      ),
    );
  }

  item(String title, String selectImage, int index) {
    bool select = (index == selectIndex);
    return GestureDetector(
      onTap: () {
        Utils.onEvent("match_tag", params: {'tag': QuickFilter.values[index]});
        widget.onSelectIndex(index);
        selectIndex = index;
        update();
      },
      child: Container(
        height: 36,
        width: 66,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          // color: select ? Colours.blue2766D6 : Colours.transparent,
          gradient: select ? const LinearGradient(
            colors: [Color(0xFFF54D4F), Color(0xFFF53C6A)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter
          ) : null,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (select)
            Image.asset(
              Utils.getImgPath(selectImage),
              width: 16
            ),
            const SizedBox(width: 2),
            QkdText(
              title,
              color: select ? Colours.white : Colours.main,
              fontSize: 12,
            )
          ]
        ),
      ),
    );
  }
}
